﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Domain.QualityInspection_Modelling;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler
{
    public class CreateQualityInspectionHandler : IRequestHandler<CreateQualityInspectionCommand, ApiResult<QualityInspection>>
    {
        private readonly IRepository<QualityInspection> _qualityRepo;
        private readonly IRepository<MaterialGroupModel> _materialGroupRepo;
        private readonly IRepository<OrderModel> _orderRepo;

        public CreateQualityInspectionHandler(
            IRepository<QualityInspection> qualityRepo,
            IRepository<MaterialGroupModel> materialGroupRepo,
            IRepository<OrderModel> orderRepo)
        {
            _qualityRepo = qualityRepo;
            _materialGroupRepo = materialGroupRepo;
            _orderRepo = orderRepo;
        }

        public async Task<ApiResult<QualityInspection>> Handle(CreateQualityInspectionCommand request, CancellationToken cancellationToken)
        { 
            var result = new ApiResult<QualityInspection>();

            // 1. 验证生产工单存在
            var order = await _orderRepo.GetValue(request.ProductionOrderId);
            if (order == null)
                return result.Fail("关联的生产工单不存在");

            // 2. 验证物料群组存在
            var materialGroup = await _materialGroupRepo.GetValue(request.MaterialGroupId);
            if (materialGroup == null)
                return result.Fail("关联的物料群组不存在");

            // 3. 验证检测数量合理性
            if (request.InspectedQuantity <= 0)
                return result.Fail("检测数量必须大于0");

            if (request.QualifiedQuantity < 0 || request.QualifiedQuantity > request.InspectedQuantity)
                return result.Fail("合格数量必须在0到检测数量之间");

            // 4. 创建质检记录
            var inspection = new QualityInspection
            {
                InspectionNumber = GenerateInspectionNo(),
                ProductionOrderId = request.ProductionOrderId,
                MaterialGroupId = request.MaterialGroupId,
                InspectedQuantity = request.InspectedQuantity,
                QualifiedQuantity = request.QualifiedQuantity,
                UnqualifiedQuantity = request.InspectedQuantity - request.QualifiedQuantity,
                Inspector = request.Inspector
            };

            // 5. 保存数据
            var dbResult = await _qualityRepo.AddAsync(inspection);
            return dbResult > 0
                ? result.AddSuccess("质检记录", inspection)
                : result.AddFail("质检记录");
        }

        // 生成唯一质检单号
        private string GenerateInspectionNo()
        {
            return $"QI{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";
        }
    }


}
